<template>
  <div class="shop-list-warpper">
    <!-- 表单 -->
    <div class="list-form">
      <el-form
        ref="ruleform"
        :model="shopForm"
        :rules="rulesForm"
        label-width="120px"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="商品分类：" prop="shopSort">
              <el-select v-model="shopForm.shopSort" placeholder="请选择商品分类" clearable filterable>
                <el-option
                  v-for="item in pageInfo.shopSortArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品状态：" prop="shopStatus">
              <el-select v-model="shopForm.shopStatus" placeholder="请选择商品状态" clearable filterable>
                <el-option
                  v-for="item in pageInfo.shopStatusArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间：" prop="createTime">
              <el-date-picker
                v-model="shopForm.createTime"
                type="datetimerange"
                :picker-options="pageInfo.pickerOptions"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: auto;"
                @change="createTimeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品价格：" prop="shopPrice">
              <div class="input-start-end">
                <el-input v-model="shopForm.shopPriceStart" />
                <span>-</span>
                <el-input v-model="shopForm.shopPriceEnd" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="商品库存：" prop="shopCount">
              <div class="input-start-end">
                <el-input v-model="shopForm.shopCountStart" />
                <span>-</span>
                <el-input v-model="shopForm.shopCountEnd" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="质量分：" prop="shopScore">
              <div class="input-start-end">
                <el-input v-model="shopForm.shopScoreStart" />
                <span>-</span>
                <el-input v-model="shopForm.shopScoreEnd" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标记美图：" prop="examineStatus">
              <el-select v-model="shopForm.examineStatus" placeholder="请选择标记美图" clearable filterable>
                <el-option
                  v-for="item in pageInfo.examineStatusArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="货号/标题包含：" prop="shopTitle">
              <el-input v-model="shopForm.shopTitle" placeholder="多个用“，”或空格分隔" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="商品ID：" prop="shopId">
              <el-input v-model="shopForm.shopId" placeholder="请输入商品ID" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标记美图：" prop="beautifulImg">
              <el-select v-model="shopForm.beautifulImg" placeholder="请选择标记美图" clearable filterable>
                <el-option
                  v-for="item in pageInfo.beautifulImgArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="货号/商品编码：" prop="shopCode">
              <el-input v-model="shopForm.shopCode" placeholder="多个用“，”或空格分隔" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleform')">搜索</el-button>
              <el-button @click="resetForm('ruleform')">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 表格 -->
    <div class="list-table">
      <div class="table-handle">
        <el-button type="primary" @click="batchEdit">批量修改</el-button>
        <el-button type="primary" plain @click="batchShelf(1)">上架</el-button>
        <el-button type="primary" plain @click="batchShelf(0)">下架</el-button>
        <el-button type="primary" plain @click="batchDelete">批量删除</el-button>
      </div>
      <el-table
        v-loading="pageInfo.isloading"
        :data="tableData"
        :header-cell-style="{ background: '#F7F8FA' }"
        border
        class="table-box"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column prop="shopCount" label="库存" width="100" />
        <el-table-column label="商品信息" width="450">
          <template slot-scope="scope">
            <div class="table-shop-info">
              <img :src="scope.row.shopImage" alt="商品图片" style="max-width: 60px; max-height: 60px; border-radius: 8px;">
              <div style="margin-left: 12px;">
                <p class="table-shop-title">
                  <span>{{ scope.row.shopTitle }}</span>
                  <span>AI换标题</span>
                </p>
                <p>
                  <span><span style="color: #999999;">ID：</span><span style="color: #4E78EF;">{{ scope.row.shopId }}</span></span>
                  <i class="el-icon-copy-document" style="margin-left: 6px; cursor: pointer;" @click="copy(scope.row.shopId)" />
                  <span style="margin-left: 20px; color: #999999;">编码/货号：{{ scope.row.shopCode }}</span>
                </p>
                <p><span style="color: #999999;">类目：</span>{{ scope.row.shopDir }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="质量分" width="150">
          <template slot-scope="scope">
            <p
              :style="{
                color: scope.row.shopScore >= 100
                  ? '#16BE4F'
                  : scope.row.shopScore >= 1
                    ? '#FFA700'
                    : '#EE0000'
              }"
            >
              {{ scope.row.shopScore }}分
            </p>
            <el-popover
              placement="right"
              trigger="hover"
              width="488"
            >
              <div class="popover-con">
                <div class="popover-header">
                  <div class="popover-title">商品质量分</div>
                  <div class="popover-time">最近检测时间：{{ scoreInfo.scoreTime }}</div>
                </div>
                <div class="popover-body">
                  <p v-for="(item, index) in scoreInfo.content" :key="index">{{ item.text }}</p>
                </div>
              </div>
              <p slot="reference" style="display: inline-block; margin-top: 6px; cursor: pointer;" @mouseenter="showScore(scope.row)">
                <i class="el-icon-refresh" style="margin-right: 6px;" />
                <span style="color: #4E78EF;">检测</span>
              </p>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="shopPrice" label="价格" width="150" />
        <el-table-column label="状态" width="150">
          <template slot-scope="scope">
            <!-- 注：2个v-for在一起后会key重复报错，拿个父盒子包起来避免报错 -->
            <div>
              <div v-for="item in pageInfo.shopStatusArr" :key="item.value">
                <p v-if="item.value === scope.row.shopStatus">{{ item.label }}</p>
              </div>
            </div>
            <div>
              <div v-for="item in pageInfo.examineStatusArr" :key="item.value">
                <p v-if="item.value === scope.row.examineStatus" :style="{color: item.color}" style="margin-top: 6px;">{{ item.label }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column fixed="right" label="操作" min-width="150">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleBackEdit(scope.row)">后台编辑</el-button>
            <el-button type="text" size="small" @click="handleOffShelf(scope.row)">下架</el-button>
            <el-button type="text" size="small" @click="handleAiSku(scope.row)">AI sku</el-button>
            <el-button type="text" size="small" style="color: #EE0000;" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="list-pagina">
        <el-pagination
          :page-size="paginaInfo.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :current-page="paginaInfo.pageIndex"
          :total="paginaInfo.total"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <el-dialog title="批量编辑" :visible.sync="editListInfo.isShow" width="1000px" class="edit-dialog">
          <edit-list @editListClick="editListClick" />
          <span slot="footer" class="dialog-footer">
            <el-button @click="editListInfo.isShow = false">取 消</el-button>
            <el-button type="primary" @click="editDialogConfirm">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { copyTool, formatToYMDHMS } from '../../utils/tool'
import { getShopGoodsPageList, getGoodsScore, productListingAndRemoval, deleteGoods } from '@/api/shop-manage'
import EditList from './components/edit-list.vue'
export default {
  components: { EditList },
  data() {
    return {
      pageInfo: {
        isloading: false,
        multipleSelection: [],
        // 商品分类。null全部，0已下架，1在售，2已删除，3草稿箱，4回收站，5其他
        shopSortArr: [
          {
            label: '已下架',
            value: 0
          },
          {
            label: '在售',
            value: 1
          },
          {
            label: '已删除',
            value: 2
          },
          {
            label: '草稿箱',
            value: 3
          },
          {
            label: '回收站',
            value: 4
          },
          {
            label: '其他',
            value: 5
          }
        ],
        // 商品状态。null全部，预售类型，0现货，1全款预售，2sku预售，3成团预售(支付后N天发货)，12现货+预售，13新预售，14阶梯发货
        shopStatusArr: [
          {
            label: '现货',
            value: 0
          },
          {
            label: '全款预售',
            value: 1
          },
          {
            label: 'sku预售',
            value: 2
          },
          {
            label: '成团预售(支付后N天发货)',
            value: 3
          },
          {
            label: '现货+预售',
            value: 12
          },
          {
            label: '新预售',
            value: 13
          },
          {
            label: '阶梯发货',
            value: 14
          }
        ],
        // 审核状态。null全部，0未提交审核，1待审核，2审核通过，3审核未通过  4-封禁
        examineStatusArr: [
          {
            label: '未提交审核',
            value: 0,
            color: '#4E78EF'
          },
          {
            label: '待审核',
            value: 1,
            color: '#FFA700'
          },
          {
            label: '审核通过',
            value: 2,
            color: '#16BE4F'
          },
          {
            label: '审核未通过',
            value: 3,
            color: '#EE0000'
          },
          {
            label: '封禁',
            value: 4,
            color: '#999999'
          }
        ],
        // null全部，1是标记过鉴图，0没标记过
        beautifulImgArr: [
          {
            label: '没标记过',
            value: 0
          },
          {
            label: '标记过鉴图',
            value: 1
          }
        ],
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        }
      },
      shopForm: {
        // 商品分类 + 商品状态 + 创建时间 + 商品价格(价格、库存、质量分暂时只用start和end，普通字段保留防止后续迭代使用。例如：shopPrice用不到)
        shopSort: null,
        shopStatus: null,
        createTime: null,
        createTimeStart: null,
        createTimeEnd: null,
        shopPrice: null,
        shopPriceStart: null,
        shopPriceEnd: null,
        // 商品库存 + 质量分 + 审核状态 + 标题包含
        shopCount: null,
        shopCountStart: null,
        shopCountEnd: null,
        shopScore: null,
        shopScoreStart: null,
        shopScoreEnd: null,
        examineStatus: null,
        shopTitle: null,
        // 商品ID + 标记美图 + 货号/商品编码
        shopId: null,
        beautifulImg: null,
        shopCode: null
      },
      rulesForm: {},
      tableData: [],
      // 页码。pageIndex：第几页；pageSize：一页几条；total：总数据量
      paginaInfo: {
        pageIndex: 1,
        pageSize: 10,
        total: 0
      },
      // 商品质量分
      scoreInfo: {
        isRequest: true,
        scoreTime: '',
        content: []
      },
      // 修改列表弹窗
      editListInfo: {
        isShow: false,
        selectLabel: '',
        selectValue: ''
      }
    }
  },
  computed: {
    ...mapState(['user'])
  },
  created() {
    this.handleGetShopGoodsPageList()
  },
  methods: {
    // 获取店铺商品列表分页查询接口
    handleGetShopGoodsPageList() {
      this.pageInfo.isloading = true
      getShopGoodsPageList({
        // 【写死部分】
        SearchGoodsSourcePlatFormCode: this.user.shopInfo.platFormCode, 		// 搜索店铺所属平台 *
        SearchGoodsSourceShopCode: this.user.shopInfo.shopCode, 	// 搜索的店铺ID，单个 *
        // 【前端传入部分】
        // 分页数据
        PageIndex: this.paginaInfo.pageIndex,
        PageSize: this.paginaInfo.pageSize,
        Total: this.paginaInfo.total, // 商品总数
        // 商品分类 + 商品状态 + 创建时间 + 商品价格
        SearchGoodsStatus: this.shopForm.shopSort,
        SearchGoodsPresaleType: this.shopForm.shopStatus,
        SearchGoodsCreateTimeMin: this.shopForm.createTimeStart, // 时间格式 ("yyyy-MM-dd HH:mm:ss")
        SearchGoodsCreateTimeMax: this.shopForm.createTimeEnd,
        SearchGoodsPriceMin: this.shopForm.shopPriceStart,
        SearchGoodsPriceMax: this.shopForm.shopPriceEnd,
        // 商品库存 + 质量分 + 审核状态 + 标题包含
        SearchGoodsStockMin: this.shopForm.shopCountStart,
        SearchGoodsStockMax: this.shopForm.shopCountEnd,
        SearchGoodsScoreMin: this.shopForm.shopScoreStart,
        SearchGoodsScoreMax: this.shopForm.shopScoreEnd,
        SearchGoodsAuditAtatus: this.shopForm.examineStatus,
        SearchGoodsTitle: this.shopForm.shopTitle,
        // 商品ID + 标记美图 + 货号/商品编码
        SearchGoodsIds: this.shopForm.shopId,
        SearchGoodsAppraisal: this.shopForm.beautifulImg,
        SearchGoodsCode: this.shopForm.shopCode
      }).then(res => {
        this.pageInfo.isloading = false
        this.paginaInfo.total = res.data.total
        this.tableData = res.data.data.map(item => ({
          ...item,
          // 库存 + 商品信息（标题 + 商品ID + 货号/商品编码 + 商品分类）
          shopCount: item.good_stock,
          shopId: item.goods_id,
          shopTitle: item.goods_name,
          shopCode: item.goods_code,
          shopImage: item.goods_image,
          shopDir: item.categoryNames, // !!!新的字段
          // 质量分 + 价格 + 状态（商品状态 + 审核状态） + 创建时间
          shopScore: item.goods_score,
          shopPrice: item.price ? `￥${item.price}` : '',
          shopStatus: item.shelfStatus, // 商品状态 0已下架，1在售，2已删除，3草稿箱，4回收站，5其他
          examineStatus: item.auditStatus, // 0未提交审核，1待审核，2审核通过，3审核未通过 4-封禁
          createTime: item.ctime
        }))
      })
    },
    // 获取商品质量分接口
    handleGetGoodsScore(val) {
      this.scoreInfo = {
        isRequest: false,
        scoreTime: '',
        content: []
      }
      getGoodsScore({
        PlatformCode: this.user.shopInfo.platFormCode, //* (目前支持快手、抖音)
        ShopCode: this.user.shopInfo.shopCode, //*
        GoodId: val.shopId// //*
      }).then(res => {
        this.scoreInfo.isRequest = true
        const result = res.data
        this.scoreInfo.scoreTime = result.scoreTime
        let i = 0
        for (const key in result.content) {
          this.scoreInfo.content.push({
            text: `${i++}、${key}：${result.content[key]}`
          })
        }
      })
    },
    // 商品上下架
    handleProductListingAndRemoval(val) {
      productListingAndRemoval({
        GoodId: val.shopId,
        State: val.state // 0-下架 1-上架
      }).then(res => {
        this.$message({ type: 'success', message: res.msg })
        this.handleGetShopGoodsPageList()
      })
    },
    // 商品删除
    handleDeleteGoods(val) {
      deleteGoods({
        GoodId: val.shopId // 商品Id *
      }).then(res => {
        this.$message({ type: 'success', message: res.msg })
        this.handleGetShopGoodsPageList()
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.handleGetShopGoodsPageList()
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 展示质量分
    showScore(row) {
      if (this.scoreInfo.isRequest) {
        this.handleGetGoodsScore({
          mallId: row.mall_id,
          shopId: row.shopId
        })
      }
    },
    // 修改
    handleEdit(row) {
      console.log(row)
      this.editListInfo.isShow = true
    },
    // 批量修改
    batchEdit() {
      if (this.pageInfo.multipleSelection.length) {
        this.editListInfo.isShow = true
      } else {
        this.$message({
          type: 'warning',
          message: '请选择要批量修改的商品'
        })
      }
    },
    // 后台编辑
    handleBackEdit(row) {
      console.log(row)
    },
    // 下架
    handleOffShelf(row) {
      console.log(row)
      this.handleProductListingAndRemoval({
        shopId: [row.shopId],
        state: 0,
        message: '下架成功'
      })
    },
    // 批量上架 && 批量下架
    batchShelf(state) {
      if (this.pageInfo.multipleSelection.length) {
        this.handleProductListingAndRemoval({
          shopId: this.pageInfo.multipleSelection.map(item => item.shopId),
          state,
          message: state === 0 ? '批量下架成功' : '批量上架成功'
        })
      } else {
        this.$message({
          type: 'warning',
          message: state === 0 ? '请选择要下架的商品' : '请选择要上架的商品'
        })
      }
    },
    handleAiSku(row) {
      console.log(row)
    },
    // 删除
    handleDelete(row) {
      this.handleDeleteGoods({
        shopId: [row.shopId],
        message: '成功'
      })
    },
    // 批量删除
    batchDelete() {
      if (this.pageInfo.multipleSelection.length) {
        this.handleDeleteGoods({
          shopId: this.pageInfo.multipleSelection.map(item => item.shopId),
          message: '批量删除成功'
        })
      } else {
        this.$message({
          type: 'warning',
          message: '请选择要删除的商品'
        })
      }
    },
    editListClick(val) {
      console.log(val)
      this.editListInfo.selectLabel = val.label
      this.editListInfo.selectValue = val.value
    },
    editDialogConfirm() {
      this.$router.push({
        path: '/shop-manage/batch-update',
        query: {
          selectLabel: this.editListInfo.selectLabel,
          selectValue: this.editListInfo.selectValue
        }
      })
    },
    createTimeChange() {
      if (this.shopForm.createTime && this.shopForm.createTime.length) {
        this.shopForm.createTimeStart = formatToYMDHMS(this.shopForm.createTime[0])
        this.shopForm.createTimeEnd = formatToYMDHMS(this.shopForm.createTime[1])
      }
    },
    handleSelectionChange(val) {
      this.pageInfo.multipleSelection = val
    },
    handleSizeChange(val) {
      this.paginaInfo.pageSize = val
      this.handleGetShopGoodsPageList()
    },
    handleCurrentChange(val) {
      this.paginaInfo.pageIndex = val
      this.handleGetShopGoodsPageList()
    },
    copy(val) {
      if (val) {
        copyTool(val)
        this.$message({ message: '复制成功', type: 'success' })
      } else {
        this.$message({ message: '无内容可复制', type: 'error' })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
p {
  margin: 0;
  line-height: 17px;
}
::v-deep {
  .el-select {
    width: 100%;
  }
}
.input-start-end {
  display: flex;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  // &:focus {
  //   outline: none;
  //   border-color: #1890ff;
  // }
  ::v-deep {
    .el-input input {
      border: none;
      &:focus {
        border-color: #00000000;
      }
    }
  }
}
.popover-con {
  line-height: 20px;
  .popover-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    border-bottom: 1px solid rgba(0,0,0,0.06);
    .popover-title {
      font-weight: 600;
    }
    .popover-time {
      color: #999999;
    }
  }
  .popover-body {
    padding: 8px 12px;
    min-height: 163px;
    p {
      line-height: 20px;
    }
  }
}
.shop-list-warpper {
  padding: 12px 20px 0;
  .list-form,
  .list-table {
    padding: 20px;
    background: #fff;
    border-radius: 4px;
  }
  .list-table {
    margin-top: 20px;
    .table-handle {
      .el-button {
        margin-left: 12px;
        &:first-of-type {
          margin-left: 0;
        }
      }
    }
    .table-box {
      margin-top: 20px;
      max-width: 100%;
      .table-shop-info {
        display: flex;
        align-items: center;
        p {
          margin-top: 4px;
          &:first-of-type {
            margin-top: 0;
          }
        }
        .table-shop-title {
          display: flex;
          align-items: center;
          span:nth-child(1) {
            flex: 1;
          }
          span:nth-child(2) {
            margin-left: 12px;
            color: #4E78EF;
            cursor: pointer;
          }
        }
      }
    }
    ::v-deep .el-popover {
      padding: 0;
    }
  }
  .list-pagina {
    display: flex;
    justify-content: flex-end;
    margin-top: 17px;
    ::v-deep {
      .el-pagination.is-background {
        .el-pager li {
          background-color: #fff;
          border: 1px solid rgba(0,0,0,0.15);
          &:not(.disabled).active {
            color: #fff;
            background-color: #1890ff;
            border: none;
          }
        }
      }
      .btn-prev,
      .btn-next {
          background-color: #fff;
          border: 1px solid rgba(0,0,0,0.15);
      }
    }
  }
  .edit-dialog {
    padding: 0 20px;
    ::v-deep {
      .el-dialog__header {
        padding: 17px 20px;
        border-bottom: 1px solid rgba(0,0,0,0.06);
      }
      .el-dialog__body {
        padding: 8px 20px 268px;
      }
      .el-dialog__footer {
        border-top: 1px solid rgba(0,0,0,0.06);
      }
    }
  }
}
</style>
